import { Init, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsPromoMsEntity } from '../entity/promo_ms';

/**
 * 促销秒杀服务
 */
@Provide()
export class GoodsPromoMsService extends BaseService {
  @InjectEntityModel(GoodsPromoMsEntity)
  promoMsEntity: Repository<GoodsPromoMsEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.promoMsEntity);
  }

  /**
   * 根据单据号获取秒杀明细
   * @param billNo 单据号
   */
  async getByBillNo(billNo: string) {
    return await this.promoMsEntity.find({
      where: { billNo, status: 1 },
      order: { billSn: 'ASC' }
    });
  }

  /**
   * 根据商品ID获取秒杀促销
   * @param goodsId 商品ID
   */
  async getByGoodsId(goodsId: string) {
    return await this.promoMsEntity.find({
      where: { goodsId, status: 1 },
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 获取所有秒杀促销明细
   */
  async getAllActiveDetails() {
    return await this.promoMsEntity.find({
      where: { status: 1 },
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 检查秒杀库存
   * @param billNo 单据号
   * @param goodsId 商品ID
   * @param quantity 购买数量
   */
  async checkSeckillStock(billNo: string, goodsId: string, quantity: number) {
    const seckillItem = await this.promoMsEntity.findOne({
      where: { billNo, goodsId, status: 1 }
    });
    
    if (!seckillItem) {
      return { available: false, message: '秒杀商品不存在' };
    }

    if (seckillItem.seckillStorNum < quantity) {
      return { available: false, message: '秒杀库存不足' };
    }

    return { available: true, seckillPrice: seckillItem.seckillPrice };
  }

  /**
   * 更新秒杀库存
   * @param billNo 单据号
   * @param goodsId 商品ID
   * @param quantity 购买数量
   */
  async updateSeckillStock(billNo: string, goodsId: string, quantity: number) {
    await this.promoMsEntity
      .createQueryBuilder()
      .update()
      .set({ seckillStorNum: () => `seckillStorNum - ${quantity}` })
      .where('billNo = :billNo', { billNo })
      .andWhere('goodsId = :goodsId', { goodsId })
      .andWhere('status = :status', { status: 1 })
      .execute();
  }
} 